package com.winshare.saleAssistant.util;

import com.winshare.saleAssistant.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class UploadValidateUtil {

    private static final List<String> correctTypeList = Arrays.asList("jpg", "jpeg", "bmp", "png", "gif");

    private static final List<String> correctImageList = Arrays.asList("FFD8FF", "89504E", "424D", "47494638");

    /**
     * 验证图片类型是否不合法
     *
     * @param type
     * @return true 不合法 false 合法
     */
    public static Boolean typeNotValidate(String type) {
        return correctTypeList.stream().noneMatch(s -> s.equalsIgnoreCase(type));
    }

    public static Boolean whetherImage(MultipartFile file) {
        byte[] b = new byte[4];
        try {
            InputStream fileInputStream = file.getInputStream();
            fileInputStream.read(b);
            String type = bytesToHexString(b).toUpperCase();
            //log.info("当前图片type：{}", type);
            return correctImageList.stream().anyMatch(s -> type.startsWith(s));
        } catch (IOException e) {
            throw new BusinessException("图片上传失败，请稍后重试");
        }
    }

    private static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
